#导入
import uvicorn
from fastapi import FastAPI,Form,Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.middleware.cors import CORSMiddleware #跨域认证中间件


#先下载multipart
#引入From

#导入路由
from api.user import api_user
from api.data_show import api_data
from api.ajax import api_ajax

#创建实例
app = FastAPI()
#实例追加中间件
app.add_middleware(CORSMiddleware,
    allow_origins='*',#允许的跨域远程
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
                   )




#将子路由包含在fastapi实例中
app.include_router(api_user,prefix="/user",tags=['用户接口'])
app.include_router(api_data,prefix="/data",tags=['数据展示'])
app.include_router(api_ajax,tags=['ajax'])

#挂载静态
app.mount("/static", StaticFiles(directory="static"), name="static")
#实例化模板文件
templates = Jinja2Templates(directory="templates")

#默认的访问
@app.get("/" ,response_class=HTMLResponse)
def index(request:Request):
    return templates.TemplateResponse(
        request=request, name="ajax_test.html", context={}
    )

'''
url的组成
协议://host:port/path?params

协议:http/https
host:IP地址本机127.0.0.1 localhost /域名
port:8000 8080 80(默认端口) 3306 
path:host之后的/hello
params: ? name=wwh

'''

#写一个接口用来识别url  http://127.0.0.1:8000/(host之后的路径)
@app.get('/hello')
def hello( ):
    return 'hello'
#写一个接口用来传参数打招呼
@app.get('/hello/{name}')
def hello(name:int):#类型要求,验证解析

    print(type(name))

    return {'name':name}

@app.get('/user')#路径不能重复
def paramsDef(name:str):
    return {'name':name}

@app.post("/form")
def getForm(id:int =Form(), username:str =Form()):#接入form值时实例化
    return {

           "data":{
               "id":id,
               "username":username
           }

    }

@app.get("/items/{id}", response_class=HTMLResponse)
async def read_item(request: Request, id: str):

    '''

    过程
    1.导入jinja2的Jinja2Templates
    2.创建实例化这个templates文件夹
    3.实例化这个Templates(文件夹位置)
    4.函数要导入Requset 和 HttpResponse
    5.如果要将数据发送到模板中并组合后发给浏览器,emplates.TemplateResponse(
    5.1参数 request=request, name=将数据发给的html模板, context=数据

    :param request:请求的作用域,
    :param id:值
    :return:
    '''

    user = {'name':'alice',"age":19,'gender':'女'}
    return templates.TemplateResponse(
        request=request, name="item.html", context={"data":user,'id':id}
    )

if __name__ == '__main__':
    #将代码部署到web
    #参数中有app = "model:app"
    uvicorn.run(app="main:app")